<?php

namespace App\Http\Controllers;

use App\Models\OssUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use OSS\Core\OssException;

class CommonController extends Controller
{
    const IMAGE_MAX_SIZE = 5000000;//5M
    const FILE_MAX_SIZE = 10000000;//10M

    const TYPE_IMAGE = 'image';
    const TYPE_FILE = 'file';

    /**
     * 上传文件
     * URL： /common/upload
     * @internal string type 文件类型：
     *  image: 保存为图片,CDN加速,大小裁切,支持{URL}/120（宽120像素）和{URL}/250（宽250像素） 两种大小格式转换
     *  file: 默认普通文件，无CDN
     * @internal string source 文件项目名，如报名项目 apply
     * @internal string {file} 表单字段名， 如表单字段 photo
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function upload(Request $request)
    {
        $type = $request->input('type', self::TYPE_FILE);
        $source = $request->input('source', 'default');
        $files = $request->files;
        if ($files->count() < 1) {
            return response('空文件',400);
        }

        $paths = [];
        $ossClient = OssUtil::getInstance();
        foreach ($files as $key => $file) {
            if ($file->getClientSize() <= 0) {
                return response($file->getErrorMessage(),400);
            }
            if ($type == self::TYPE_IMAGE) {
//                限制文件格式
                if (!starts_with($file->getMimeType(), 'image/')) {
                    Log::warning('文件格式不正确:' . $file->getMimeType());
                    continue;
                }
                //限制文件大小
                if ($file->getClientSize() > self::IMAGE_MAX_SIZE) {
                    Log::warning('文件大小超出限制:' . $file->getClientSize());
                    continue;
                }
            } else {
                if ($file->getClientSize() > self::FILE_MAX_SIZE) {
                    Log::warning('文件大小超出限制:' . $file->getClientSize());
                    continue;
                }
            }
            //保存到本地
            $path = $request->file($key)->store($type . '/' . $source . '/' . $key);
            if (!$path) {
                \Log::warning('上传到本地出错: path:' . $request->file($key)->path());
                continue;
            }
            try {
                if ($type == self::TYPE_IMAGE) {
                    $ossClient->uploadFile(OssUtil::OSS_PHOTO_BUCKET, 'storage/' . $path, $request->file($key));
                    $paths[] = env('PHOTO_STORAGE_URL') . $path;
                } else {
                    $ossClient->uploadFile(OssUtil::OSS_FILES_BUCKET, 'storage/' . $path, $request->file($key));
                    $paths[] = env('FILES_STORAGE_URL') . $path;
                }
            } catch (OssException $e) {
                \Log::warning('上传到OSS出错: path:' . $path . ' error:' . $e->getMessage());
                $paths[] = env('LOCAL_STORAGE_URL') . $path;
            }
        };
        if (count($paths) == 1) {
            return response()->json($paths[0]);
        }
        return response()->json($paths);
    }
}
